﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;

namespace Utils.Helpers
{
    public class HttpHelper
    {
        /// <summary>
        /// 检查一个站点是否可以请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static bool CheckGet(string url, int timeOut = 30) 
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("url");

            var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
            var result = httpClient.GetAsync(url).Result;
            return result.StatusCode == System.Net.HttpStatusCode.OK;
        }

        /// <summary>
        /// 发送Get同步请求
        /// </summary>
        /// <param name="host"></param>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <param name="contenType"></param>
        /// <param name="headers"></param>
        public static string HttpGet(string host, string url, int timeOut = 30,
            string contenType = "application/json", Dictionary<string, string> headers = null)
        {
            using (HttpClient client = HttpClientFactory.GetClient(host, timeOut))
            {
                if (headers != null)
                    foreach (var head in headers)
                        client.DefaultRequestHeaders.Add(head.Key, head.Value);

                var response = client.GetAsync(url);
                return response.Result.Content.ReadAsStringAsync().Result;
            }
        }
    }
}
